import {
	APP
} from '../config/app.config.js'

const {
	APP_NAME,
	APP_VERSION
} = APP

/**
 * 基于uni封装的localStorage数据缓存，提供4种方法
 * 1. set(key,value)
 * 2. get(key)
 * 3. remove(key)
 * 4. clear()
 */

export const storage = {
	set(key, value) {
		return uni.setStorageSync(`${APP_NAME}_${key}`, JSON.stringify(value))
	},
	get(key) {
		if (uni.getStorageSync(`${APP_NAME}_${key}`) == '') {
			return ''
		}
		return JSON.parse(uni.getStorageSync(`${APP_NAME}_${key}`))
	},
	remove(key) {
		try {
			uni.removeStorageSync(`${APP_NAME}_${key}`)
		} catch (e) {
			console.log(e)
		}
	},
	clear() {
		try {
			uni.clearStorageSync();
		} catch (e) {
			console.log(e)
		}
	}
}

/**
 * 根据生日计算年龄
 */
export function getAgeByBirthday(strBirthday) {
	var returnAge;
	var strBirthdayArr = strBirthday.split("-");
	var birthYear = strBirthdayArr[0];
	var birthMonth = strBirthdayArr[1];
	var birthDay = strBirthdayArr[2];

	var d = new Date();
	var nowYear = d.getFullYear();
	var nowMonth = d.getMonth() + 1;
	var nowDay = d.getDate();

	if (nowYear == birthYear) {
		returnAge = 0; //同年 则为0岁
	} else {
		var ageDiff = nowYear - birthYear; //年之差
		if (ageDiff > 0) {
			if (nowMonth == birthMonth) {
				var dayDiff = nowDay - birthDay; //日之差
				if (dayDiff < 0) {
					returnAge = ageDiff - 1;
				} else {
					returnAge = ageDiff;
				}
			} else {
				var monthDiff = nowMonth - birthMonth; //月之差
				if (monthDiff < 0) {
					returnAge = ageDiff - 1;
				} else {
					returnAge = ageDiff;
				}
			}
		} else {
			returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天
		}
	}
	return returnAge; //返回周岁年龄
}

// 将数组拉平
export const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
